﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using bdnt_pets_system.Tools;
using bdnt_pets_system_Entity;
using System.Windows.Data;
using System.Globalization;
using System.Collections.ObjectModel;
using bdnt_pets_system.Resources;

namespace bdnt_pets_system.PageViews.Failures
{
    public partial class PartSelectControl : BaseUserControl
    {
        DataServiceReference.DataServiceClient dataClient;
        List<Tbl_StationMemebers> cuStationMemembers = null;

        public List<Tbl_StationMemebers> CuStationMemembers
        {
            get { return cuStationMemembers; }
            set { cuStationMemembers = value; }
        }
        void InitEvent()
        {
            dataClient.GetPartStationListByConditonCompleted += new EventHandler<DataServiceReference.GetPartStationListByConditonCompletedEventArgs>(dataClient_GetPartStationListByConditonCompleted);

            dataClient.GetStationMemebersByCoditionCompleted += new EventHandler<DataServiceReference.GetStationMemebersByCoditionCompletedEventArgs>(dataClient_GetStationMemebersByCoditionCompleted);

            cbShopName.SelectionChanged += new SelectionChangedEventHandler(cbShopName_SelectionChanged);
            cbStationName.SelectionChanged += new SelectionChangedEventHandler(cbStationName_SelectionChanged);
            tbProductionNo.KeyDown += new KeyEventHandler(tbProductionNo_KeyDown);
            tbVINNo.KeyDown += new KeyEventHandler(tbVINNo_KeyDown);
            dataClient.GetVehicleByProNoOrVinNoCompleted += new EventHandler<DataServiceReference.GetVehicleByProNoOrVinNoCompletedEventArgs>(dataClient_GetVehicleByProNoOrVinNoCompleted);
            tbPartName.KeyDown += new KeyEventHandler(tbPartName_KeyDown);
        }

        void tbPartName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                QueryCoditionData();
            }
        }

        void dataClient_GetVehicleByProNoOrVinNoCompleted(object sender, DataServiceReference.GetVehicleByProNoOrVinNoCompletedEventArgs e)
        {
            if (e.Result == null)
            {
                if (MessageBox.Show("数据库中没有此车辆数据，是否要添加？", "提示", MessageBoxButton.OKCancel) ==
                     MessageBoxResult.Cancel)
                    return;
                NewVehicleWindow nvw = new NewVehicleWindow(new Tbl_Vehicle()
                {
                    VINNo = tbVINNo.Text,
                    ProducitonNo = tbProductionNo.Text
                });
                nvw.Show();
                nvw.Closed += new EventHandler(nvw_Closed);
                //tbErrors.Text = MyStrings.sjkzmycclsj;// "数据库中没有此车辆数据";
            }
            else
            {
                tbErrors.Text = "";
                CuTbl_FailureRecord.VINNo = e.Result.VINNo;
                CuTbl_FailureRecord.ProductionNo = e.Result.ProducitonNo;
                tbCarColorV.Text = e.Result.VColor;
                tbVConfigurationV.Text = SessionManager.IsCN_ZH ? e.Result.VConfigurationName : e.Result.en_VConfigurationName;
                tbNsColorV.Text = e.Result.InteriorColor;
                tbVINNo.Foreground = tbProductionNo.Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        void nvw_Closed(object sender, EventArgs e)
        {
            var cuo = sender as NewVehicleWindow;
            if (cuo.DialogResult == true)
            {
                tbErrors.Text = "";
                CuTbl_FailureRecord.VINNo = cuo.CuTbl_Vehicle.VINNo;
                CuTbl_FailureRecord.ProductionNo = cuo.CuTbl_Vehicle.ProducitonNo;
                tbCarColorV.Text = cuo.CuTbl_Vehicle.VColor;
                tbVConfigurationV.Text = SessionManager.IsCN_ZH ? cuo.CuTbl_Vehicle.VConfigurationName : cuo.CuTbl_Vehicle.en_VConfigurationName;
                tbNsColorV.Text = cuo.CuTbl_Vehicle.InteriorColor;
                tbVINNo.Foreground = tbProductionNo.Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        void tbVINNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                dataClient.GetVehicleByProNoOrVinNoAsync("", tbVINNo.Text);
            }
        }

        void tbProductionNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                dataClient.GetVehicleByProNoOrVinNoAsync(tbProductionNo.Text, "");
            }
        }

        void dataClient_GetPartStationListByConditonCompleted(object sender, DataServiceReference.GetPartStationListByConditonCompletedEventArgs e)
        {
            cuAllParts = e.Result;
            cuConditionParts = cuAllParts.Where(p => p.StationId == cuStationId).ToList();
            LoadParts();
        }

        //void tbPartName_TextChanged(object sender, RoutedEventArgs e)
        //{
        //    QueryCoditionData();
        //}

        //void tbPartName_Populating(object sender, PopulatingEventArgs e)
        //{
        //    if (e != null)
        //        e.Cancel = true;//一定要指定已处理此处理，取消此事件
        //    if (cuAllParts == null)
        //        return;
        //    var partNames = cuAllParts.Where(p => p.StationId == cuStationId && p.PartName.Contains(tbPartName.Text.Trim())).Select(p => p.PartName).ToList();
        //    tbPartName.ItemsSource = partNames;
        //    tbPartName.PopulateComplete();
        //}

        public Tbl_FailureRecord CuTbl_FailureRecord
        {
            get { return spCondition.DataContext as Tbl_FailureRecord; }
            set { spCondition.DataContext = value; }
        }

        //默认查询条件
        public PartSelectControlPageCondition selectFailureRecord = new PartSelectControlPageCondition()
        {
            ProductionNo = MyStrings.qsrsclsh,
            VINNo = MyStrings.qsrclsbm,
            StationName = MyStrings.qxzgw,
            EmpName = MyStrings.qxzjyy,
            Position = MyStrings.qxzwz,
            Fauilre = MyStrings.qxzgz,
            CheckTime = MyStrings.qxzjcrq
        };

        public PartSelectControl()
        {
            InitializeComponent();
            dataClient = new DataServiceReference.DataServiceClient();
            InitData();
        }

        void InitData()
        {
            tbProductionNo.Foreground = tbVINNo.Foreground = new SolidColorBrush(Colors.Gray);
            tbProductionNo.SetBinding(TextBox.TextProperty, new Binding("ProductionNo")
            {
                Mode = BindingMode.TwoWay
            });
            tbProductionNo.Tag = selectFailureRecord.ProductionNo;
            tbVINNo.SetBinding(TextBox.TextProperty, new Binding("VINNo")
            {
                Mode = BindingMode.TwoWay
            });
            tbVINNo.Tag = selectFailureRecord.VINNo;

            dpCheckDate.SetBinding(DatePicker.SelectedDateProperty, new Binding("CheckTime")
            {
                Mode = BindingMode.TwoWay,
                StringFormat = "yyyy-MM-dd"
            });
            dpCheckDate.Tag = selectFailureRecord.CheckTime;

            CuTbl_FailureRecord = new Tbl_FailureRecord()
            {
                ProductionNo = selectFailureRecord.ProductionNo,
                VINNo = selectFailureRecord.VINNo,
                CheckTime = DateTime.Now
            };
            InitEvent();
            LoadComboxData();
        }

        void LoadComboxData()
        {
            if (string.IsNullOrEmpty(SessionManager.CurrentUser.StationIds))
                return;
            dataClient.GetStationMemebersByCoditionAsync(SessionManager.CurrentUser.StationIds);
        }

        public int cuStationId = 0;
        void dataClient_GetStationMemebersByCoditionCompleted(object sender, DataServiceReference.GetStationMemebersByCoditionCompletedEventArgs e)
        {
            cuStationMemembers = e.Result.ToList();
            var shops = HelpTools.DistinctList(cuStationMemembers.Select(p => new SimpleObject<int, string>()
            {
                Item1 = p.ShopId,
                Item2 = SessionManager.IsCN_ZH ? p.ShopName : p.en_ShopName
            }).ToList()).OrderBy(p => p.Item1).ToList();

            cbShopName.ItemsSource = shops;
            cbShopName.DisplayMemberPath = "Item2";
            cbShopName.SelectedValuePath = "Item1";
            cbShopName.SelectedIndex = shops.Count > 0 ? 0 : -1;

            //查询部件
            QueryAllData();
        }

        void cbShopName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cuo = sender as ComboBox;
            if (cuo.SelectedValue == null)
                return;
            var cuShopId = cuo.SelectedValue.ToString();
            if (cuStationMemembers == null || cuStationMemembers.Count < 1)
                return;

            var stations = HelpTools.DistinctList(cuStationMemembers.Where(p => p.ShopId.ToString() == cuShopId).Select(p => new SimpleObject<int, string>()
            {
                Item1 = p.StationId,
                Item2 = SessionManager.IsCN_ZH ? p.StationName : p.en_StationName
            }).OrderBy(p => p.Item1).ToList()).ToList();
            cuStationId = stations.FirstOrDefault() != null ? stations.FirstOrDefault().Item1 : 0; ;
            cbStationName.ItemsSource = stations;
            cbStationName.DisplayMemberPath = "Item2";
            cbStationName.SelectedValuePath = "Item1";
            cbStationName.SelectedIndex = stations.Count > 0 ? 0 : -1;
        }

        void cbStationName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cuo = sender as ComboBox;
            if (cuo.SelectedValue == null)
                return;
            var sv = cuo.SelectedValue.ToString();
            cuStationId = Int32.Parse(sv);
            QueryCoditionData();
            if (cuStationMemembers == null || cuStationMemembers.Count < 1)
                return;

            var emps = HelpTools.DistinctList(cuStationMemembers.Where(p => p.StationId.ToString() == sv).Select(p => new SimpleObject<int, string>()
            {
                Item1 = p.EmpId,
                Item2 = p.EmpName
            }).OrderBy(p => p.Item1).ToList()).ToList();
            cbEmpName.ItemsSource = emps;
            cbEmpName.DisplayMemberPath = "Item2";
            cbEmpName.SelectedValuePath = "Item1";
            cbEmpName.SelectedIndex = emps.Count > 0 ? 0 : -1;
        }

        #region 查询

        //数据库查询条件对象 
        void QueryAllData()
        {
            //dataClient.GetPartStationListByConditonAsync
            dataClient.GetPartStationListByConditonAsync(SessionManager.CurrentUser.StationIds);
        }

        void QueryCoditionData()
        {
            if (cuAllParts == null)
                return;

            cuConditionParts = cuAllParts.Where(p => p.StationId == cuStationId && (p.PartName.ToLower().Contains(tbPartName.Text) || p.en_PartName.ToLower().Contains(tbPartName.Text))).ToList();
            LoadParts();
        }

        Tbl_PartSta_Relation cuPartInfo;
        ObservableCollection<Tbl_PartSta_Relation> cuAllParts;
        List<Tbl_PartSta_Relation> cuConditionParts = new List<Tbl_PartSta_Relation>();

        void LoadParts()
        {
            wpParts.Children.Clear();
            if (cuConditionParts.Count() < 1)
                return;
            foreach (var item in cuConditionParts)
            {
                Border bd = new Border();
                HyperlinkButton hb = new HyperlinkButton() { Tag = item };
                if (cuPartInfo != null && cuPartInfo.PartNo == item.PartNo && cuPartInfo.StationId == item.StationId)
                {
                    bd.BorderBrush = new SolidColorBrush(Colors.Red);
                    //#D0D7E3
                    //bd.Background = new SolidColorBrush(Colors.Gray); #E6EBF1 #E8EDF3
                    bd.Background = new SolidColorBrush(HelpTools.HtmlToColor("#D0D7E3"));
                }
                hb.Click += new RoutedEventHandler(hb_Click);
                TextBlock tb = new TextBlock()
                {
                    Margin = new Thickness(5),
                    TextWrapping = TextWrapping.Wrap
                };

                tb.Text = SessionManager.IsCN_ZH ? item.PartName + "(" + item.en_PartName + ")" : item.en_PartName;
                hb.Content = tb;
                bd.Child = hb;
                wpParts.Children.Add(bd);
            }
        }

        public SaveFailuresManagerControl sfC;
        void hb_Click(object sender, RoutedEventArgs e)
        {
            cbEmpName.IsEnabled = cbShopName.IsEnabled = cbStationName.IsEnabled = false;
            var cuo = (sender as HyperlinkButton);
            cuPartInfo = cuo.Tag as Tbl_PartSta_Relation;
            if (sfC == null)
            {
                sfC = new SaveFailuresManagerControl(cuPartInfo);
                sfC.Tag = this;
                gdMC.Children.Add(sfC);
            }
            else
            {
                if (sfC.CuPartInfo != null)
                {
                    if (cuPartInfo.StationId != sfC.CuPartInfo.StationId || (cuPartInfo.PartNo != sfC.CuPartInfo.PartNo && cuPartInfo.StationId == sfC.CuPartInfo.StationId))
                    {
                        sfC.wpFailures.Children.Clear();
                        sfC.wpPositions.Children.Clear();
                        sfC.selectPositionInfo = null;
                        sfC.selectFailure.Clear();
                        sfC.CuPartInfo = cuPartInfo;
                        sfC.QueryData();
                    }
                }
            }
            sfC.Visibility = System.Windows.Visibility.Visible;
            gdParts.Visibility = System.Windows.Visibility.Collapsed;
            LoadParts();
        }

        #endregion


        /// <summary>
        /// 字段验证方法
        /// </summary>
        public bool BindgExpression(Tbl_FailureRecord cuFr)
        {
            bool va = true;
            if (string.IsNullOrEmpty(cuFr.ProductionNo) || cuFr.ProductionNo == selectFailureRecord.ProductionNo)
            {
                //tbErrors.Text = selectFailureRecord.ProductionNo;
                va = false; ;
            }

            if ((string.IsNullOrEmpty(cuFr.VINNo) || cuFr.VINNo == selectFailureRecord.VINNo) && !va)
            {
                tbErrors.Text = MyStrings.lshhsbmbnwk;// "流水号或识别码不能为空";
                return false;
            }

            if (cuFr.FailureId == 0)
            {
                tbErrors.Text = selectFailureRecord.Fauilre;
                return false;
            }
            if (!cuFr.CheckTime.HasValue)
            {
                tbErrors.Text = selectFailureRecord.CheckTime;
                return false;
            }
            if (cbStationName.SelectedValue == null)
            {
                tbErrors.Text = selectFailureRecord.StationName;
                return false;
            }
            if (cbEmpName.SelectedValue == null)
            {
                tbErrors.Text = selectFailureRecord.EmpName;
                return false;
            }

            if (string.IsNullOrEmpty(cuFr.PositionNo))
            {
                tbErrors.Text = selectFailureRecord.Position;
                return false;
            }
            if (cuFr.FailureId == 0)
            {
                tbErrors.Text = selectFailureRecord.Fauilre;
                return false;
            }
            return true;
        }
    }

    public class PartSelectControlPageCondition
    {
        public string ProductionNo { get; set; }
        public string VINNo { get; set; }
        public string StationName { get; set; }
        public string EmpName { get; set; }
        public string Position { get; set; }
        public string Fauilre { get; set; }
        public string CheckTime { get; set; }
    }
}
